<template>
  <div class="clothes-detail-container">
    <!-- 顶部返回按钮 -->
    <div class="detail-header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <van-icon
        name="ellipsis"
        class="more-icon"
        @click="showActionSheet = true"
      />
    </div>

    <!-- 衣物图片 -->
    <div class="image-container">
      <img
        :src="
          outfit.finalOutfitImage ||
          'https://gd-hbimg.huaban.com/f5773e512a1d749bce5dfd456ac8958c23d1148edf16-z6vbGy_fw658webp'
        "
        class="clothes-image"
      />
    </div>
    <!-- 属性详情 -->
    <div class="details-section">
      <div class="section-title">
        <span>属性详情</span>
        <div class="edit-text" @click="editClothes">
          <button class="edit-text-button">修改</button>
          <van-icon name="arrow" color="#999999" size="14" />
        </div>
      </div>
      <div class="details-table" @click="editClothes">
        <div class="table-cell">
          <span class="detail-label">{{
            outfit.description || "添加备注"
          }}</span>
        </div>

        <div class="table-cell">
          <span class="detail-label">适合场景：</span>
          <div class="detail-value">
            <span
              v-for="(value, index) in outfit.occasions || []"
              :key="index"
              >{{ value || "" }}</span
            >
          </div>
        </div>
        <div class="table-cell">
          <span class="detail-label">季节：</span>
          <div class="detail-value">
            <span v-for="(value, index) in outfit.seasons || []" :key="index">{{
              value || ""
            }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 编辑搭配 -->
    <div class="edit-button-container">
      <div @click="editOutfit" class="edit-button-item">
        <div class="edit-button-icon">+</div>
        <div class="edit-button">编辑搭配</div>
      </div>
    </div>
    <!-- 操作菜单图片弹窗 -->
    <div class="action-sheet-content" v-show="showActionSheet">
      <img
        :src="outfit.finalOutfitImage"
        alt=""
        style="
          display: block;
          margin: auto;
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          left: 0;
          right: 0;
          width: 80%;
        "
      />
    </div>
    <van-popup
      v-model:show="showActionSheet"
      position="bottom"
      :style="{ height: '20%', backgroundColor: '#fbfbfb', padding: '20px' }"
      z-index="999"
      :close-on-click-overlay="false"
      round
      closeable
    >
      <div class="popup-options">
        <div class="option-item" @click="saveImage">
          <div class="action-bt">
            <img src="/src/assets/icons/download.svg" alt="" />
          </div>
          <span>保存图片</span>
        </div>
        <div class="option-item" @click="deleteClothes">
          <div class="action-bt">
            <img src="/src/assets/icons/del.svg" alt="" />
          </div>
          <span>删除单品</span>
        </div>
      </div>
    </van-popup>
    <!-- 确认弹窗 -->
    <van-dialog
      v-model:show="showConfirmDialog"
      type="warning"
      @confirm="confirmDelete"
      @cancel="cancelDelete"
      show-cancel-button
      cancel-button-text="取消"
      confirm-button-text="确定"
      title="确认删除"
      message="确定要删除这件衣物吗？此操作不可撤销。"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useOutfitStore } from "../store/outfit";
import { useUserStore } from "../store/user";
import { showToast } from "vant";

const router = useRouter();
const route = useRoute();
const outfitStore = useOutfitStore();
const userStore = useUserStore();

// 搭配ID
const outfitId = ref(route.params.id);

// 搭配数据
const outfit = ref({});

// 弹窗状态
const showActionSheet = ref(false);
const showConfirmDialog = ref(false);

// 获取搭配详情
const fetchOutfitDetail = async () => {
  try {
    const res = await outfitStore.fetchOutfitDetail(outfitId.value);

    // 确保res是对象类型
    if (typeof res === "object" && res !== null) {
      outfit.value = res;
    } else {
      console.warn("获取到的搭配数据格式异常，使用默认值");
      outfit.value = {
        season: [],
        occasions: [],
        finalOutfitImage: "",
        description: "",
      };
    }
  } catch (error) {
    console.error("获取搭配详情失败:", error);
    console.error("错误详情:", error.response?.data);
    // 显示友好的错误提示
    showToast({
      message: "获取搭配详情失败，请稍后重试",
      position: "bottom",
    });
    // 设置默认数据
    outfit.value = {
      season: [],
      occasions: [],
      finalOutfitImage: "",
      description: "",
    };
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 编辑搭配
const editClothes = () => {
  router.push(`/outfits/edit/${outfitId.value}`);
};

// 删除衣物（弹出确认）
const deleteClothes = () => {
  showConfirmDialog.value = true;
  showActionSheet.value = false;
};

// 确认删除
const confirmDelete = async () => {
  try {
    await outfitStore.deleteOutfit(outfitId.value);
    showToast({ message: "删除成功", position: "bottom" });
    setTimeout(() => {
      router.push("/outfits");
    }, 1000);
  } catch (error) {
    console.error("删除搭配失败:", error);
    showToast({ message: "删除失败，请重试", position: "bottom" });
  } finally {
    showConfirmDialog.value = false;
  }
};

// 取消删除
const cancelDelete = () => {
  showConfirmDialog.value = false;
};

// 保存图片
const saveImage = () => {
  showActionSheet.value = false;

  try {
    // 获取搭配图片元素
    const outfitImageElement = document.querySelector(".clothes-image");

    if (!outfitImageElement || !outfitImageElement.src) {
      showToast({ message: "未找到图片资源", position: "bottom" });
      return;
    }

    // 创建一个新的图片元素用于下载
    const img = new Image();

    // 处理跨域图片 - 在H5环境中这很重要
    img.crossOrigin = "anonymous";

    img.onload = () => {
      try {
        // 创建canvas元素
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");

        // 设置canvas尺寸与图片一致
        canvas.width = img.width;
        canvas.height = img.height;

        // 在canvas上绘制图片
        ctx.drawImage(img, 0, 0);

        // 创建下载链接
        const link = document.createElement("a");

        // 生成图片文件名，使用搭配ID
        const fileName = `outfit_${outfitId.value}.png`;

        // 设置下载链接属性
        link.download = fileName;
        link.href = canvas.toDataURL("image/png");

        // 触发下载 - 在某些H5环境中需要特殊处理
        document.body.appendChild(link);

        // 兼容不同浏览器的点击方式
        if (typeof link.click === "function") {
          link.click();
        } else {
          // 对于不支持click方法的环境
          const event = new MouseEvent("click");
          link.dispatchEvent(event);
        }

        // 移除链接元素
        setTimeout(() => {
          document.body.removeChild(link);
        }, 0);

        // 显示成功提示
        showToast({
          message: "图片保存成功",
          position: "bottom",
        });
      } catch (error) {
        console.error("保存图片失败:", error);
        showToast({
          message: "保存图片失败，请重试",
          position: "bottom",
        });
      }
    };

    img.onerror = () => {
      showToast({
        message: "图片加载失败",
        position: "bottom",
      });
    };

    // 设置图片源，触发加载
    img.src = outfit.finalOutfitImage || outfitImageElement.src;
  } catch (error) {
    console.error("保存图片过程中出现错误:", error);
    showToast({
      message: "保存图片时发生错误",
      position: "bottom",
    });
  }
};

// 编辑搭配
const editOutfit = () => {
  router.push(`/outfits/create/${outfitId.value}`);
};

// 初始化
onMounted(() => {
  fetchOutfitDetail();
});
</script>

<style scoped>
.clothes-detail-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 20px;
}
.action-sheet-content {
  background-color: #ffffff;
  width: 80%;
  height: 55%;
  position: fixed;
  bottom: 25%;
  left: 50%;
  z-index: 1000;
  transform: translateX(-50%);
  border-radius: 16px;
}
.popup-options {
  position: absolute;
  top: 50%;
  transform: translateY(-25%);
  display: flex;
  gap: 20px;
}

.detail-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background-color: #f8f8f8;
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); */
}

.back-icon,
.more-icon {
  font-size: 20px;
  color: #000000;
}

.image-container {
  width: 100%;
  background-color: #f8f8f8;
  padding: 20px;
  text-align: center;
}

.clothes-image {
  /* max-width: 50%;
  max-height: 400px; */
  object-fit: contain;
}

.info-section {
  background-color: white;
  padding: 20px;
  margin-top: 10px;
}

.clothes-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.clothes-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.tag {
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.category-tag {
  background-color: #409eff;
}

.season-tag {
  background-color: #67c23a;
}

.occasion-tag {
  background-color: #e6a23c;
}

.action-buttons {
  display: flex;
  gap: 20px;
}

.action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: white;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
}

.action-btn:hover {
  border-color: #409eff;
  color: #409eff;
}

.action-btn van-icon {
  margin-right: 6px;
}
.option-item {
  text-align: center;
}
.option-item span {
  color: #878787;
}
.action-bt {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #f8f8f8;
  width: 35px;
  height: 35px;
  margin: 0 auto;
}
.details-section {
  background-color: #ffffff;
  margin: 20px 20px 80px 20px;
  border-radius: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
}

.details-table {
  display: flex;
  flex-direction: column;
  width: 100%;
  /* border: 1px solid #f0f0f0; */
  border-radius: 8px;
  background-color: #f8f8f8;
  overflow: hidden;
  padding: 10px 10px;
}

.table-cell {
  padding: 7px 0px 7px 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 3px;
  border-bottom: 2px solid #f0f0f0;
}

.details-section {
  position: relative;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #000000;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-text {
  display: flex;
  align-items: center;
  gap: 4px;
}
.edit-text-button {
  background: none;
  border: none;
  color: #999999;
  cursor: pointer;
  font-size: 14px;
}

.table-cell:last-child {
  border-bottom: none;
}

.clothes-description {
  padding: 16px 0;
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

/* 第一排 */
.table-cell:first-child {
  min-width: 100%;
  padding-left: 0;
}

.detail-label {
  font-size: 14px;
  color: #999;
  word-break: break-all;
}

.detail-value {
  font-size: 14px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 5px;
}

.color-display {
  display: flex;
  align-items: center;
  gap: 5px;
}

.color-swatch {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #e4e7ed;
}

.notes-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}

.bottom-actions {
  display: flex;
  gap: 10px;
  padding: 16px 20px;
  background-color: white;
  margin-top: 20px;
}

.bottom-actions .van-button {
  flex: 1;
  height: 44px;
  border-radius: 8px;
}

@media (max-width: 768px) {
  .detail-header {
    padding: 14px 16px;
  }

  .image-container {
    padding: 16px;
  }

  .info-section,
  .details-section,
  .notes-section {
    padding: 16px;
  }

  .bottom-actions {
    padding: 14px 16px;
  }

  .details-section,
  .notes-section {
    padding-bottom: 16px;
  }

  /* 在移动端添加适当的底部间距 */
}

/* 底部提示 */
.bottom-hint {
  text-align: center;
  color: #8c8c8c;
  font-size: 14px;
  padding: 20px 0;
}

.edit-button-container {
  /* 固定屏幕底部 */
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 16px 32px 16px;
  background-color: white;
}
.edit-button-item {
  display: flex;
  align-items: center;
  gap: 4px;
}
.edit-button-icon {
  font-size: 20px;
  border-radius: 50%;
  background-color: #6c63ff;
  color: white;
  width: 22px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.edit-button {
  font-size: 18px;
  color: #6c63ff;
  border-radius: 8px;
  font-weight: bold;
}
</style>
